var app = require('http').createServer(handle);
var io = require('socket.io').listen(app);
var Snake = require('./utils/Snake');
var Grid = require('./utils/Grid');
var fs = require('fs');
var url = require('url');
var port = 3100;

app.listen(port);

function handle(req, res) {
  var path = '';
  if (req.url === '/') {
    path = __dirname + '/view/index.html';
  } else {
    path = __dirname + url.parse(req.url).pathname;
  }
  fs.readFile(path,
    function (err, data) {
      if (err) {
        res.writeHead(500);
        return res.end('Error loading ' + path);
      }
      res.writeHead(200);
      res.end(data);
    });
}

var grid = new Grid(40, function () {
  io.sockets.emit('message', this);
  this.deadSnakes().forEach(function (snake) {
    io.sockets.emit('tip', snake.id + ' 挂了');
  });
  this.revivedSnakes().forEach(function (snake) {
    snake.changeRevive();
    io.sockets.emit('tip', snake.id + ' 复活了');
  });
});

io.on('connection', function (socket) {
  console.log("Connection " + socket.id + ".");
  grid.push(socket.id);
  socket.broadcast.emit('tip', 'Welcome ' + socket.id);
  socket.on('message', function (msg) {
    //io.sockets.emit('message', msg);
    //socket.broadcast.emit('message',msg);
    //socket.emit('message', msg);
    grid.receiveMsg(socket.id, msg);
  });
  socket.on('disconnect', function () {
    console.log("Connection " + socket.id + " terminated.");
    grid.killSnake(socket.id);
  });
});